package com.analysis.server.service;

import cn.hutool.core.util.ObjUtil;
import com.analysis.server.model.LogTemplate;
import com.analysis.server.model.SlowSqlResult;
import com.analysis.server.repository.ILogTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 日志分析服务类
 * 用于分析MyBatis日志文件，检测慢SQL  合适小文件
 */
@Service
public class LogAnalysisOldService {

    private static final Logger logger = LoggerFactory.getLogger(LogAnalysisService.class);

    @Autowired
    private ILogTemplateService logTemplateRepository;

    // 日志时间格式
    private static final DateTimeFormatter LOG_TIME_FORMATTER = 
        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    // 正则表达式模式
    private static final Pattern PREPARING_PATTERN = 
        Pattern.compile("(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}) \\[.*?\\] DEBUG (.*?) - ==>  Preparing: (.+)");
    
    private static final Pattern PARAMETERS_PATTERN = 
        Pattern.compile("(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}) \\[.*?\\] DEBUG (.*?) - ==> Parameters: (.+)");
    
    private static final Pattern TOTAL_PATTERN = 
        Pattern.compile("(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}) \\[.*?\\] TRACE (.*?) - <==      Total: (.+)");
    
    private static final Pattern ROW_PATTERN = 
        Pattern.compile("(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}) \\[.*?\\] TRACE (.*?) - <==        Row: (.+)");
    
    // 慢SQL阈值（毫秒）
    private static final long SLOW_SQL_THRESHOLD_30S = 30000;  // 30秒
    private static final long SLOW_SQL_THRESHOLD_1MIN = 60000; // 1分钟
    
    /**
     * 分析日志文件，检测慢SQL
     * @param file 上传的日志文件
     * @return 慢SQL分析结果列表
     */
    public List<SlowSqlResult> analyzeLogFile(MultipartFile file) throws IOException {
        List<SlowSqlResult> slowSqlResults = new ArrayList<>();
        
        // 用于缓存正在执行的SQL信息
        Map<String, SqlExecutionInfo> sqlExecutionMap = new HashMap<>();
        
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(file.getInputStream(), "UTF-8"))) {
            
            String line;
            int lineNumber = 0;
            
            while ((line = reader.readLine()) != null) {
                lineNumber++;
                
                // 解析Preparing行
                Matcher preparingMatcher = PREPARING_PATTERN.matcher(line);
                if (preparingMatcher.find()) {
                    String timestamp = preparingMatcher.group(1);
                    String mapperName = preparingMatcher.group(2);
                    String sql = preparingMatcher.group(3);
                    
                    LocalDateTime startTime = parseDateTime(timestamp);
                    if (startTime != null) {
                        String sqlKey = mapperName + ":" + sql.hashCode();
                        sqlExecutionMap.put(sqlKey, new SqlExecutionInfo(sql, mapperName, startTime, lineNumber, line));
                    }
                    continue;
                }
                
                // 解析Parameters行
                Matcher parametersMatcher = PARAMETERS_PATTERN.matcher(line);
                if (parametersMatcher.find()) {
                    String timestamp = parametersMatcher.group(1);
                    String mapperName = parametersMatcher.group(2);
                    String parameters = parametersMatcher.group(3);
                    
                    LocalDateTime paramTime = parseDateTime(timestamp);
                    if (paramTime != null) {
                        String sqlKey = mapperName + ":" + parameters.hashCode();
                        SqlExecutionInfo info = sqlExecutionMap.get(sqlKey);
                        if (info != null) {
                            info.setParameters(parameters);
                        }
                    }
                    continue;
                }
                
                // 解析Total行（SQL执行完成）
                Matcher totalMatcher = TOTAL_PATTERN.matcher(line);
                if (totalMatcher.find()) {
                    String timestamp = totalMatcher.group(1);
                    String mapperName = totalMatcher.group(2);
                    String total = totalMatcher.group(3);
                    
                    LocalDateTime endTime = parseDateTime(timestamp);
                    if (endTime != null) {
                        processSqlCompletion(sqlExecutionMap, mapperName, endTime, lineNumber, line, slowSqlResults);
                    }
                    continue;
                }
                
                // 解析Row行（SQL执行完成）
                Matcher rowMatcher = ROW_PATTERN.matcher(line);
                if (rowMatcher.find()) {
                    String timestamp = rowMatcher.group(1);
                    String mapperName = rowMatcher.group(2);
                    String row = rowMatcher.group(3);
                    
                    LocalDateTime endTime = parseDateTime(timestamp);
                    if (endTime != null) {
                        processSqlCompletion(sqlExecutionMap, mapperName, endTime, lineNumber, line, slowSqlResults);
                    }
                }
            }
        }
        
        return slowSqlResults;
    }
    
    /**
     * 处理SQL执行完成
     */
    private void processSqlCompletion(Map<String, SqlExecutionInfo> sqlExecutionMap, 
                                    String mapperName, LocalDateTime endTime, 
                                    int lineNumber, String logLine, 
                                    List<SlowSqlResult> slowSqlResults) {
        
        // 查找对应的SQL执行信息
        SqlExecutionInfo info = null;
        String foundKey = null;
        
        for (Map.Entry<String, SqlExecutionInfo> entry : sqlExecutionMap.entrySet()) {
            if (entry.getValue().getMapperName().equals(mapperName)) {
                info = entry.getValue();
                foundKey = entry.getKey();
                break;
            }
        }
        
        if (info != null && foundKey != null) {
            long duration = java.time.Duration.between(info.getStartTime(), endTime).toMillis();
            
            // 检查是否为慢SQL
            if (duration >= SLOW_SQL_THRESHOLD_30S) {
                SlowSqlResult result = new SlowSqlResult(
                    info.getSql(),
                    info.getStartTime(),
                    endTime,
                    info.getMapperName(),
                    info.getParameters(),
                    info.getLineNumber(),
                    info.getLogLine()
                );
                slowSqlResults.add(result);
            }
            
            // 从缓存中移除已完成的SQL
            sqlExecutionMap.remove(foundKey);
        }
    }
    
    /**
     * 解析日期时间字符串
     */
    private LocalDateTime parseDateTime(String timestamp) {
        try {
            return LocalDateTime.parse(timestamp, LOG_TIME_FORMATTER);
        } catch (DateTimeParseException e) {
            return null;
        }
    }
    
    /**
     * SQL执行信息内部类
     */
    private static class SqlExecutionInfo {
        private String sql;
        private String mapperName;
        private LocalDateTime startTime;
        private String parameters;
        private int lineNumber;
        private String logLine;
        
        public SqlExecutionInfo(String sql, String mapperName, LocalDateTime startTime, 
                              int lineNumber, String logLine) {
            this.sql = sql;
            this.mapperName = mapperName;
            this.startTime = startTime;
            this.lineNumber = lineNumber;
            this.logLine = logLine;
        }
        
        // Getters and Setters
        public String getSql() { return sql; }
        public void setSql(String sql) { this.sql = sql; }
        
        public String getMapperName() { return mapperName; }
        public void setMapperName(String mapperName) { this.mapperName = mapperName; }
        
        public LocalDateTime getStartTime() { return startTime; }
        public void setStartTime(LocalDateTime startTime) { this.startTime = startTime; }
        
        public String getParameters() { return parameters; }
        public void setParameters(String parameters) { this.parameters = parameters; }
        
        public int getLineNumber() { return lineNumber; }
        public void setLineNumber(int lineNumber) { this.lineNumber = lineNumber; }
        
        public String getLogLine() { return logLine; }
        public void setLogLine(String logLine) { this.logLine = logLine; }
    }
    /**
     * 根据模板动态解析日志文件（使用数据库中保存的正则表达式）
     */
    public List<SlowSqlResult> analyzeLogFileWithTemplate(MultipartFile file, Long templateId) throws IOException {
        LogTemplate template = logTemplateRepository.getLogTemplateById(templateId);
        if (ObjUtil.isNull(template)) throw new IllegalArgumentException("模板不存在");

        logger.info("=== 开始分析日志文件 ===");
        logger.info("模板ID: {}", templateId);
        logger.info("模板名称: {}", template.getName());
        logger.info("Preparing正则: {}", template.getPreparingRegex());
        logger.info("Parameters正则: {}", template.getParametersRegex());
        logger.info("Total正则: {}", template.getTotalRegex());
        logger.info("线程匹配策略: {}", template.getThreadMatchingStrategy());

        // 使用数据库中保存的正则表达式
        Pattern preparingPattern = Pattern.compile(template.getPreparingRegex());
        Pattern parametersPattern = Pattern.compile(template.getParametersRegex());
        Pattern totalPattern = Pattern.compile(template.getTotalRegex());

        List<SlowSqlResult> slowSqlResults = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream(), "UTF-8"))) {
            String line;
            int lineNumber = 0;
            LocalDate today = LocalDate.now();
            // 使用更智能的存储结构：Map<线程名, Map<类名, SqlExecutionInfo>>
            Map<String, Map<String, SqlExecutionInfo>> threadSqlMap = new HashMap<>();

            while ((line = reader.readLine()) != null) {
                lineNumber++;

                // 尝试匹配 Preparing 行
                Matcher preparingMatcher = preparingPattern.matcher(line);
                if (preparingMatcher.find()) {
                    logger.info("=== 匹配 Preparing 行 ===");
                    logger.info("行号: {}", lineNumber);
                    logger.info("日志内容: {}", line);

                    String timeStr = getGroupSafely(preparingMatcher, "time");
                    String sql = getGroupSafely(preparingMatcher, "sql");
                    String mapperName = getGroupSafely(preparingMatcher, "class");
                    String thread = getGroupSafely(preparingMatcher, "thread");

                    logger.info("提取字段 - 时间: {}, SQL: {}, 类名: {}, 线程: {}", timeStr, sql, mapperName, thread);

                    LocalDateTime time = parseTimeString(timeStr, today);

                    if (sql != null && time != null) {
                        // 为每个线程创建独立的类名映射
                        threadSqlMap.computeIfAbsent(thread, k -> new HashMap<>())
                                   .put(mapperName, new SqlExecutionInfo(sql, mapperName, time, lineNumber, line));
                        logger.info("记录SQL开始 - 线程: {}, 类名: {}, SQL: {}", thread, mapperName, sql);
                        logger.info("当前线程数: {}, 总SQL数: {}", threadSqlMap.size(), 
                                  threadSqlMap.values().stream().mapToInt(Map::size).sum());
                    }
                    continue;
                }

                // 尝试匹配 Parameters 行
                Matcher parametersMatcher = parametersPattern.matcher(line);
                if (parametersMatcher.find()) {
                    logger.info("=== 匹配 Parameters 行 ===");
                    logger.info("行号: {}", lineNumber);
                    logger.info("日志内容: {}", line);

                    String timeStr = getGroupSafely(parametersMatcher, "time");
                    String params = getGroupSafely(parametersMatcher, "params");
                    String mapperName = getGroupSafely(parametersMatcher, "class");
                    String thread = getGroupSafely(parametersMatcher, "thread");

                    logger.info("提取字段 - 时间: {}, 参数: {}, 类名: {}, 线程: {}", timeStr, params, mapperName, thread);

                    if (params == null || params.trim().isEmpty()) {
                        params = extractParametersManually(line);
                        logger.info("手动提取参数: {}", params);
                    }

                    if (params != null && !params.trim().isEmpty()) {
                        Map<String, SqlExecutionInfo> classMap = threadSqlMap.get(thread);
                        if (classMap != null) {
                            SqlExecutionInfo info = classMap.get(mapperName);
                            if (info != null) {
                                info.setParameters(params);
                                logger.info("✓ 成功更新参数 - 线程: {}, 类名: {}, 参数: {}", thread, mapperName, params);
                            } else {
                                logger.info("✗ 未找到对应的SQL执行信息 - 线程: {}, 类名: {}", thread, mapperName);
                            }
                        } else {
                            logger.info("✗ 未找到线程的SQL执行信息 - 线程: {}", thread);
                        }
                    } else {
                        logger.warn("⚠ 参数提取失败，跳过此行");
                            }
                    continue;
                    }

                // 尝试匹配 Total/Row 行
                Matcher totalMatcher = totalPattern.matcher(line);
                if (totalMatcher.find()) {
                    logger.info("=== 匹配 Total/Row 行 ===");
                    logger.info("行号: {}", lineNumber);
                    logger.info("日志内容: {}", line);

                    String timeStr = getGroupSafely(totalMatcher, "time");
                    String mapperName = getGroupSafely(totalMatcher, "class");
                    String thread = getGroupSafely(totalMatcher, "thread");

                    logger.info("提取字段 - 时间: {}, 类名: {}, 线程: {}", timeStr, mapperName, thread);

                    LocalDateTime endTime = parseTimeString(timeStr, today);

                    if (endTime != null) {
                        Map<String, SqlExecutionInfo> classMap = threadSqlMap.get(thread);
                        if (classMap != null) {
                            SqlExecutionInfo foundInfo = classMap.get(mapperName);

                            if (foundInfo != null && foundInfo.getStartTime() != null) {
                                long duration = java.time.Duration.between(foundInfo.getStartTime(), endTime).toMillis();
                                logger.info("SQL完成 - SQL: {}, 耗时: {}ms, 参数: {}", foundInfo.getSql(), duration, foundInfo.getParameters());

                                if (duration >= template.getSqlTimeoutThreshold()) {
                                SlowSqlResult result = new SlowSqlResult(
                                            foundInfo.getSql(),
                                            foundInfo.getStartTime(),
                                            endTime,
                                            foundInfo.getMapperName(),
                                            foundInfo.getParameters(),
                                            foundInfo.getLineNumber(),
                                            foundInfo.getLogLine()
                                );
                                slowSqlResults.add(result);
                                    logger.info("✓ 发现慢SQL - SQL: {}, 耗时: {}ms", foundInfo.getSql(), duration);
                                }
                            } else {
                                logger.info("✗ 未找到对应的SQL执行信息 - 线程: {}, 类名: {}", thread, mapperName);
                            }

                            // 移除已完成的SQL
                            classMap.remove(mapperName);
                            
                            // 如果线程没有更多SQL，清理线程记录
                            if (classMap.isEmpty()) {
                                threadSqlMap.remove(thread);
                            }
                        } else {
                            logger.info("✗ 未找到线程的SQL执行信息 - 线程: {}", thread);
                    }
                }
            }
        }
        }

        logger.info("=== 分析完成 ===");
        logger.info("发现慢SQL数量: {}", slowSqlResults.size());
        return slowSqlResults;
    }

    /**
     * 手动提取参数（当正则表达式失败时的备用方案）
     */
    private String extractParametersManually(String line) {
        try {
            int startIndex = line.indexOf("==> Parameters: ");
            if (startIndex != -1) {
                String params = line.substring(startIndex + "==> Parameters: ".length()).trim();
                logger.info("手动提取参数: {}", params);
                return params;
            }
        } catch (Exception e) {
            logger.error("手动提取参数失败: {}", e.getMessage());
        }
        return null;
    }

    /**
     * 测试模板正则表达式
     */
    public List<Map<String, Object>> testTemplateRegex(LogTemplate template, String logText) {
        List<Map<String, Object>> results = new ArrayList<>();

        if (template.getPreparingRegex() != null && !template.getPreparingRegex().isEmpty()) {
            Map<String, Object> preparingResult = testRegex(template.getPreparingRegex(), logText, "Preparing");
            results.add(preparingResult);
        }

        if (template.getParametersRegex() != null && !template.getParametersRegex().isEmpty()) {
            Map<String, Object> parametersResult = testRegex(template.getParametersRegex(), logText, "Parameters");
            results.add(parametersResult);
        }

        if (template.getTotalRegex() != null && !template.getTotalRegex().isEmpty()) {
            Map<String, Object> totalResult = testRegex(template.getTotalRegex(), logText, "Total");
            results.add(totalResult);
        }

        return results;
    }

    /**
     * 测试单个正则表达式
     */
    private Map<String, Object> testRegex(String regex, String logText, String type) {
        Map<String, Object> result = new HashMap<>();
        result.put("type", type);

        try {
            // 对于时间字段，尝试多种时间格式的正则表达式
            String adjustedRegex = adjustTimeRegex(regex);
            
            logger.debug("测试类型: {}", type);
            logger.debug("测试文本: {}", logText);
            logger.debug("原始正则: {}", regex);
            logger.debug("调整后正则: {}", adjustedRegex);
            
            Pattern pattern = Pattern.compile(adjustedRegex);
            Matcher matcher = pattern.matcher(logText);

            if (matcher.find()) {
                result.put("matched", true);

                List<Map<String, String>> fields = new ArrayList<>();
                
                // 提取命名捕获组名称（使用原始正则表达式）
                List<String> groupNames = extractNamedGroups(regex);
                
                // 按位置获取捕获组值（与前端逻辑保持一致）
                for (int i = 0; i < groupNames.size(); i++) {
                    String groupName = groupNames.get(i);
                    String value = matcher.group(i + 1); // 按位置获取，从1开始
                    
                    if (value != null) {
                        Map<String, String> field = new HashMap<>();
                        field.put("name", groupName);
                        field.put("value", value);
                        fields.add(field);
                        logger.debug("提取字段: {} = {}", groupName, value);
                    }
                }

                result.put("fields", fields);
            } else {
                result.put("matched", false);
                result.put("fields", new ArrayList<>());
                logger.debug("正则匹配失败");
            }
        } catch (Exception e) {
            result.put("matched", false);
            result.put("error", e.getMessage());
            result.put("fields", new ArrayList<>());
            logger.error("正则测试异常: {}", e.getMessage());
        }

        return result;
    }

    /**
     * 调整时间正则表达式以支持多种时间格式
     */
    private String adjustTimeRegex(String regex) {
        // 支持以下时间格式：
        // 1. 2025-07-12 10:00:00:000 (带毫秒，冒号分隔)
        // 2. 2025-07-12 10:00:00.000 (带毫秒，点分隔)
        // 3. 2025-07-12 10:00:00 (不带毫秒)
        
        // 将严格的时间格式改为灵活格式
        String adjustedRegex = regex.replaceAll(
            "\\(\\?<time>\\\\d\\{4\\}-\\\\d\\{2\\}-\\\\d\\{2\\} \\\\d\\{2\\}:\\\\d\\{2\\}:\\\\d\\{2\\}:\\\\d\\{3\\}\\)",
            "(?<time>\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}(?::\\d{3}|\\.\\d{3})?)"
        );
        
        // 如果上面的替换没有生效，尝试匹配不带毫秒的格式
        if (adjustedRegex.equals(regex)) {
            adjustedRegex = regex.replaceAll(
                "\\(\\?<time>\\\\d\\{4\\}-\\\\d\\{2\\}-\\\\d\\{2\\} \\\\d\\{2\\}:\\\\d\\{2\\}:\\\\d\\{2\\}\\)",
                "(?<time>\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}(?::\\d{3}|\\.\\d{3})?)"
            );
        }
        
        // 如果还是没有替换，尝试更宽松的匹配
        if (adjustedRegex.equals(regex)) {
            adjustedRegex = regex.replaceAll(
                "\\\\d\\{4\\}-\\\\d\\{2\\}-\\\\d\\{2\\} \\\\d\\{2\\}:\\\\d\\{2\\}:\\\\d\\{2\\}:\\\\d\\{3\\}",
                "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}(?::\\d{3}|\\.\\d{3})?"
            );
        }
        
        logger.debug("原始正则: {}", regex);
        logger.debug("调整后正则: {}", adjustedRegex);
        
        return adjustedRegex;
    }

    /**
     * 提取正则表达式中的命名捕获组名称
     */
    private List<String> extractNamedGroups(String regex) {
        List<String> groupNames = new ArrayList<>();
        Pattern groupPattern = Pattern.compile("\\(\\?<(\\w+)>");
        Matcher groupMatcher = groupPattern.matcher(regex);
        
        while (groupMatcher.find()) {
            groupNames.add(groupMatcher.group(1));
        }
        
        return groupNames;
    }

    /**
     * 根据线程匹配策略生成键
     */
    private String generateKey(String thread, String mapperName, String strategy) {
        if (thread == null) return mapperName;

        switch (strategy) {
            case "prefix":
                return thread.split("-")[0] + "|" + mapperName;
            case "contains":
                return thread + "|" + mapperName;
            case "exact":
            default:
                return thread + "|" + mapperName;
        }
    }

    /**
     * 创建 Preparing 行的正则表达式
     */
    private String createPreparingRegex(String template) {
        return templateToRegex(template);
    }

    /**
     * 创建 Parameters 行的正则表达式
     */
    private String createParametersRegex(String template) {
        String parametersTemplate = template.replace("Preparing:", "Parameters:");
        return templateToRegex(parametersTemplate);
    }

    /**
     * 创建 Total/Row 行的正则表达式
     */
    private String createTotalRegex(String template) {
        String totalTemplate = template.replace("==>  Preparing:", "<==      Total:");
        return templateToRegex(totalTemplate);
    }

    /**
     * 安全地获取正则分组，如果分组不存在返回null
     */
    private String getGroupSafely(Matcher matcher, String groupName) {
        try {
            return matcher.group(groupName);
        } catch (IllegalArgumentException e) {
            return null;
        }
    }

    /**
     * 从模板中提取所有字段名
     */
    private Set<String> extractTemplateFields(String template) {
        Set<String> fields = new HashSet<>();
        Pattern fieldPattern = Pattern.compile("\\{(\\w+)}");
        Matcher matcher = fieldPattern.matcher(template);
        while (matcher.find()) {
            fields.add(matcher.group(1));
        }
        return fields;
    }

    /**
     * 解析时间字符串
     */
    private LocalDateTime parseTimeString(String timeStr, LocalDate today) {
        if (timeStr == null) return null;

        try {
            // 支持多种时间格式
            if (timeStr.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}:\\d{3}")) {
                // 格式: 2025-07-12 10:00:00:000
                return LocalDateTime.parse(timeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS"));
            } else if (timeStr.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\.\\d{3}")) {
                // 格式: 2025-07-12 10:00:00.000
                return LocalDateTime.parse(timeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
            } else if (timeStr.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}")) {
                // 格式: 2025-07-12 10:00:00
                return LocalDateTime.parse(timeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            } else if (timeStr.matches("\\d{2}:\\d{2}:\\d{2}\\.\\d{3}")) {
                // 格式: 10:00:00.000
                return LocalDateTime.of(today, LocalTime.parse(timeStr, DateTimeFormatter.ofPattern("HH:mm:ss.SSS")));
            } else if (timeStr.matches("\\d{2}:\\d{2}:\\d{2}")) {
                // 格式: 10:00:00
                return LocalDateTime.of(today, LocalTime.parse(timeStr, DateTimeFormatter.ofPattern("HH:mm:ss")));
            } else {
                logger.warn("不支持的时间格式: {}", timeStr);
                return null;
            }
        } catch (Exception e) {
            logger.error("时间解析失败: {}, 错误: {}", timeStr, e.getMessage());
            return null;
        }
    }



    // 模板转正则
    public static String templateToRegex(String template) {
        String regex = template.replace("[", "\\[")
                .replace("]", "\\]")
                .replace(".", "\\.");
        Pattern fieldPattern = Pattern.compile("\\{(\\w+)}");
        Matcher matcher = fieldPattern.matcher(regex);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String field = matcher.group(1);
            String replacement;
            
            // 根据字段类型生成不同的正则表达式
            switch (field) {
                case "time":
                    // 支持多种时间格式：2025-07-12 10:00:00:000 或 2025-07-12 10:00:00.000 或 2025-07-12 10:00:00
                    replacement = "(?<time>\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}(?::\\d{3}|\\.\\d{3})?)";
                    break;
                case "thread":
                    replacement = "(?<thread>[^\\]]+)";
                    break;
                case "level":
                    replacement = "(?<level>\\w+)";
                    break;
                case "class":
                    replacement = "(?<class>[\\w\\.]+)";
                    break;
                case "sql":
                    replacement = "(?<sql>.+)";
                    break;
                case "params":
                    replacement = "(?<params>.+)";
                    break;
                case "total":
                    replacement = "(?<total>\\d+)";
                    break;
                case "row":
                    replacement = "(?<row>.+)";
                    break;
                case "msg":
                    replacement = "(?<msg>.+)";
                    break;
                default:
                    replacement = "(?<" + field + ">.*?)";
                    break;
            }
            matcher.appendReplacement(sb, replacement);
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}